/**
 * [description]
 * @author lu.hong 2016-09-09
 * @param  {[type]} $scope            [description]
 * @param  {[type]} $http             [description]
 * @param  {[type]} serverService     [description]
 * @param  {[type]} i18nService       [description]
 * @param  {[type]} dialogService     [description]
 * @param  {[type]} codeEditorService [description]
 * @param  {[type]} ngNotify          [description]
 * @param  {String} $compile)         {	$("[data-toggle [description]
 * @return {[type]}                   [description]
 */
angular.module('app').controller('graphController', ['$scope','$log','$http','Upload','serverService','graphService','i18nService','dialogService','asciiTableService','codeEditorService','ngNotify','$compile',
	function($scope,$log,$http,Upload,serverService,graphService,i18nService,dialogService,asciiTableService,codeEditorService,ngNotify,$compile) {
	
	$("[data-toggle='tooltip']").tooltip({delay:{show:1000,hide:100}});//提示插件
	var myChart = graphService.graphInit("codeGraph");//初始化图表插件

	$scope.editorHasContent = false;
	$scope.showCodeContent = true;
	$scope.showChartContent = false;
	$scope.showTableContent = false;
	$scope.showTextContent = false;
	$scope.showErrorsContent = false;
	$scope.showGraphBtn = false;//用于判断是否显示图的按钮
	$scope.showErrorBtn = false;
	$scope.showRowsBtn = false;
	$scope.showTextBtn = false;
	$scope.showCodeBtn = true;
	//显示导入导出的按钮
	$scope.showExportAndImport = false;

	$scope.activeBtn = '';

	$scope.codeText = "";
	$scope.row_num = 0;
	$scope.timeDiff = 0;
	$scope.hasLink = false;//用于判断是否显示关系标签
	$scope.showRes = false;//用于判断是否显示结果的提示


	$scope.firstCode = "CREATE (PaulBlythe:Person {name:'Paul Blythe'})";

	var opt= {autofocus: true};
	var editor_cypher = codeEditorService.init("codemirror_cypher",opt);

	editor_cypher.on('change',function(){
		if(editor_cypher.getValue()){
			$scope.editorHasContent = true;
		}else{
			$scope.editorHasContent = false;
		}
		//判断下$apply()有没有进行，没有就手动调用
		if(!$scope.$$phase) { 
			$scope.$apply();
		}
	});
	//清除code
	$scope.clearContent = function(){
		editor_cypher.setValue("");
		editor_cypher.focus();
	};
	//收藏code
	$scope.star = function(){
		var code = editor_cypher.getValue();
		if($scope.editorHasContent && code){
			console.log("收藏code,star方法");
			//console.log(code);
		}
	};
	//执行code
	$scope.execScript = function(){
		$scope.showExportAndImport = false;
		var dt1 = new Date();
		//获取编辑器中的代码
		var code = editor_cypher.getValue();
		$scope.codeText = code;
		if($scope.editorHasContent && code){
			console.log("执行code,execScript方法");
			//console.log(code);
			//参数
			var data = {
				"statements":[
					{
						"statement":code,
						"parameters":null,
						"resultDataContents":["row","graph"],
						"includeStats":true
					}
				]
			};
			$scope.showRes = false;
			//发送请求
			serverService.sendEditorCode(data,function(response){
				//获得返回的数据
				//console.log(response);
				graphService.ResToGraphJSON(response,[],function(data,rawdata){
					if(!data){
						$scope.showErrorBtn = true;
						$scope.showRowsBtn = false;
						$scope.showTextBtn = false;
						$scope.showGraphBtn = false;
						$scope.showCodeBtn = false;
						var errors = rawdata.errors;
						$scope.errorsCode = errors[0].code;
						$scope.errorsMessage = errors[0].message;

						$scope.setActive("errors");
						return false;
					}else{
						$scope.showErrorBtn = false;
						$scope.showRowsBtn = true;
						$scope.showTextBtn = true;
						$scope.showGraphBtn = true;
						$scope.showCodeBtn = false;
					}
					console.log(data);
					//显示导入导出
					$scope.showExportAndImport = true;
					//数据传到html
					$scope.nodeLeng = data.nodes.length;
					$scope.linkLeng = data.links.length;
					$scope.categories = data.categories;
					$scope.linktype = data.linktype;
					if(data.linktype.length>0){
						$scope.hasLink = true;
					}else{
						$scope.hasLink = false;
					}
					//得到数据后显示结果提示
					$scope.showRes = true;
					//返回的数据中存在节点时，才去绘制图
					if(data.nodes.length > 0){
						$scope.setActive("graph");
						graphService.drawGraph(myChart,data);
					}else{
						$scope.showGraphBtn = false;
						$scope.setActive("text");
					}

					var columns = rawdata.results[0].columns;
					var row_d = rawdata.results[0].data;
					var stats = rawdata.results[0].stats;
					if(columns.length || row_d.length){
						//绘制表格
						var asciiTable = asciiTableService.drawAsciiTable(columns,row_d);
						var normalTable = asciiTableService.drawNormalTable(columns,row_d);
						$("#asciiTable").html(asciiTable);
						$("#normalTable").html(normalTable);
						$scope.row_num = row_d.length;
					}else{
						$scope.showRowsBtn = false;
						$scope.setStatsText(stats);
					}
					var dt2 = new Date();
					$scope.timeDiff = dt2.getTime()-dt1.getTime();//时间差的毫秒数
				});
			});
		}
	};

	
	//legend点击事件
	$scope.legendClick = function(legend){
		$scope.legendActive = legend;
		if($scope.twiceActive){
			$scope.twiceActive = false;
		}else{
			$scope.twiceActive = true;
		}
		myChart.dispatchAction({
		    type: 'legendToggleSelect',
		    name: legend
		});
	};

	//
	$scope.copyToCode = function(codeText){
		editor_cypher.setValue(codeText);
		editor_cypher.focus();
	};



	

	//判断显示图还是表格 graph rows text errors warn code
	$scope.setActive = function(param){
		$scope.activeBtn = param;
		if(param == "graph"){
			$scope.showChartContent = true;
			$scope.showTableContent = false;
			$scope.showTextContent = false;
			$scope.showErrorsContent = false;
			$scope.showCodeContent = false;
		}
		if(param == "rows"){
			$scope.showChartContent = false;
			$scope.showTableContent = true;
			$scope.showTextContent = false;
			$scope.showErrorsContent = false;
			$scope.showCodeContent = false;
		}
		if(param == "text"){
			$scope.showChartContent = false;
			$scope.showTableContent = false;
			$scope.showTextContent = true;
			$scope.showErrorsContent = false;
			$scope.showCodeContent = false;
		}
		if(param == "errors"){
			$scope.showChartContent = false;
			$scope.showTableContent = false;
			$scope.showTextContent = false;
			$scope.showErrorsContent = true;
			$scope.showCodeContent = false;
		}
		if(param == "code"){
			$scope.showChartContent = false;
			$scope.showTableContent = false;
			$scope.showTextContent = false;
			$scope.showErrorsContent = false;
			$scope.showCodeContent = true;
		}
	};


	$scope.setStatsText = function(stats){
		$scope.nodes_created = 0;
		$scope.nodes_deleted = 0;
		$scope.properties_set = 0;
		$scope.relationships_created = 0;
		$scope.relationship_deleted = 0;
		$scope.labels_added = 0;
		$scope.labels_removed = 0;
		$scope.indexes_added = 0;
		$scope.indexes_removed = 0;
		$scope.constraints_added = 0;
		$scope.constraints_removed = 0;

		$.each(stats,function(idx,data){
			if(idx == "nodes_created" && data){
				$scope.nodes_created = data;
			}
			if(idx == "nodes_deleted" && data){
				$scope.nodes_deleted = data;
			}
			if(idx == "properties_set" && data){
				$scope.properties_set = data;
			}
			if(idx == "relationships_created" && data){
				$scope.relationships_created = data;
			}
			if(idx == "relationship_deleted" && data){
				$scope.relationship_deleted = data;
			}
			if(idx == "labels_added" && data){
				$scope.labels_added = data;
			}
			if(idx == "labels_removed" && data){
				$scope.labels_removed = data;
			}
			if(idx == "indexes_added" && data){
				$scope.indexes_added = data;
			}
			if(idx == "indexes_removed" && data){
				$scope.indexes_removed = data;
			}
			if(idx == "constraints_added" && data){
				$scope.constraints_added = data;
			}
			if(idx == "constraints_removed" && data){
				$scope.constraints_removed = data;
			}
		});
	};

	$scope.testShowText = function(param){
		if(param > 0){
			return true;
		}else{
			return false;
		}
	};



	$scope.isActive = function(param){
		if($scope.activeBtn == param){
			return true;
		}else{
			return false;
		}
	};

	//exportFile 导出
	$scope.exportFile = function(){
		var query = $scope.codeText;
		var filepath = $scope.export_file;
		$log.log(filepath);
		$log.log(query);
		if(!filepath){
			ngNotify.set('请先输入目标路径', 'warn');
			return false;
		}
		var url = serverService.settings.endpoint.export;
		var data = {
				"query" : query,
				"filepath":filepath
		}
		serverService.sendPost(url,data,function(){
			$log.log("发送导出请求");
		})
	};

	//importFile 导入
	$scope.importFile = function(){
		var filepath = $scope.import_file;
		$log.log(filepath);
		if(!filepath){
			ngNotify.set('请先选择导入文件', 'warn');
			return false;
		}
		var url = serverService.settings.endpoint.import;
		var data = {
				"filepath":filepath
		}
		serverService.sendPost(url,data,function(){
			$log.log("发送导出请求");
		})

		/**
		serverService.sendPost(url,data,function(){
			$log.log("发送导入请求");
		})
		**/
		/***
		var headers = serverService.returnHeaders();
        Upload.upload({
            //服务端接收
            url: url,
            //上传的同时带的参数
            data: data,
            headers: headers, // only for html5
            file: filepath
        }).progress(function (evt) {
            //进度条
            var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
            //console.log('progess:' + progressPercentage + '%' + evt.config.file.name);
            console.log('progess:' + progressPercentage + '%' + evt.config.file);
        }).success(function (data, status, headers, config) {
            //上传成功
            console.log('file ' + config.file.name + 'uploaded. Response: ' + data);
            $scope.uploadImg = data;
        }).error(function (data, status, headers, config) {
            //上传失败
            console.log('error status: ' + status);
        });
        **/
	};
}]);